package org.example.reggie.exception;

import org.example.reggie.result.ResultData;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理
 * 基于代AOP来对这些异常进行拦截
 * @ControllerAdvice(annotations = {RestController.class, Controller.class})主要处理添加了@RestController、@Controller注解的类产生的异常
 * @ResponseBody 需要有返回值
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
public class GlobalExceptionHandler {


    /**
     * @ExceptionHandler({异常类型.class,异常类型.class})
     * @param ex 异常对象
     * @return
     */
    @ExceptionHandler({SQLIntegrityConstraintViolationException.class,NullPointerException.class})
    public ResultData<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        if (ex.getMessage().contains("Duplicate entry")){
            String []split=ex.getMessage().split(" ");
            String errorMessage = split[2] + "已存在";
            return ResultData.error(errorMessage);
        }
        return  ResultData.error("请求异常");
    }

    /**
     * 捕捉自定义异常 CustomerException
     * @param ex
     * @return
     */
    @ExceptionHandler({CustomerException.class,NullPointerException.class})
    public ResultData<String> exceptionHandler(CustomerException ex){
        return  ResultData.error(ex.getMessage());
    }
}
